const mysql = require('mysql2/promise');

// 创建数据库连接池
const db = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASS || '',
  database: process.env.DB_NAME || 'ht_service',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  acquireTimeout: 60000,
  timeout: 60000
});

// 数据库连接测试和日志
db.getConnection()
  .then(connection => {
    console.log('✅ [数据库] 连接成功 -', {
      host: process.env.DB_HOST || 'localhost',
      port: process.env.DB_PORT || 3306,
      database: process.env.DB_NAME || 'ht_service',
      user: process.env.DB_USER || 'root',
      timestamp: new Date().toISOString()
    });
    connection.release();
  })
  .catch(err => {
    console.error('❌ [数据库] 连接失败 -', {
      error: err.message,
      code: err.code,
      errno: err.errno,
      host: process.env.DB_HOST || 'localhost',
      port: process.env.DB_PORT || 3306,
      database: process.env.DB_NAME || 'ht_service',
      user: process.env.DB_USER || 'root',
      timestamp: new Date().toISOString()
    });
  });

// 监听连接池事件
db.on('connection', (connection) => {
  console.log('🔗 [数据库] 新连接建立 - ID:', connection.threadId);
});

db.on('error', (err) => {
  console.error('💥 [数据库] 连接池错误 -', {
    error: err.message,
    code: err.code,
    timestamp: new Date().toISOString()
  });
});

module.exports = db;